<?php
class SearchesController extends AppController {

	var $name = 'Searches';
	var $helpers = array('Html', 'Form');
	
	function index () {
		$this->loadModel('Gender');
		$genders = $this->Gender->find('list');
		$this->set(compact('genders'));
		
		$this->loadModel('Region');
		$regions = $this->Region->find('list');
		$this->set(compact('regions'));
		
		$this->loadModel('Educationdoctype');
		$educationdoctypes = $this->Educationdoctype->find('list');
		$this->set(compact('educationdoctypes'));
		
		$this->loadModel('Learningtype');
		$learningtypes = $this->Learningtype->find('list');
		$this->set(compact('learningtypes'));
		
		// для установки факультета и курса
		$this->loadModel('Facultet');
/* 		$facultets = $this->Facultet->find('list');
		$this->set(compact('facultets')); */
		// читаем из сессии какие факультеты доступны
		$facultetsettings = $this->Session->read('FacultetsSettings');
		
		$tmpfacultets = $this->Facultet->find('all', array('conditions' => array('Facultet.id' => $facultetsettings), 'recursive' => -1));
		//debug($facultetsettings);
		foreach ($tmpfacultets as $facultet):
		$facultets[$facultet['Facultet']['id']] = $facultet['Facultet']['name'];
		endforeach;
		$this->set(compact('facultets'));
	}
	
	function update_profession () {
	
		if(!empty($this->data['Search']['facultet_id'])) {
			$facultet_id = $this->data['Search']['facultet_id'];
			$this->loadModel('Profession');
			$options = $this->Profession->find('list', array('conditions' => array ('Profession.facultet_id' => $facultet_id)));
			$this->set(compact('options'));
		}
	}
		
	function update_course () {
		if(!empty($this->data['Search']['profession_id'])) {
			$profession_id = $this->data['Search']['profession_id'];
			$this->loadModel('Course');
			$options = $this->Course->find('list', array('conditions' => array ('Course.profession_id' => $profession_id)));
			$this->set(compact('options'));
		}
	}
	
	function update_studentgroup () {
		if(!empty($this->data['Search']['course_id'])) {
			$course_id = $this->data['Search']['course_id'];
			$this->loadModel('Studentgroup');
			$options = $this->Studentgroup->find('list', array('conditions' => array ('Studentgroup.course_id' =>  $course_id)));
			$this->set(compact('options'));
		}
	}	
	function findstudent() {
		
		// загружаем модели
		$this->loadModel('Gender');
		$genders = $this->Gender->find('list');
		$this->set(compact('genders'));
		
		$this->loadModel('Course');
		$courses = $this->Course->find('all');
		$this->set(compact('courses'));
		
		$this->loadModel('Educationdoctype');
		$educationdoctypes = $this->Educationdoctype->find('list');
		$this->set(compact('educationdoctypes'));
		
		$this->loadModel('Learningtype');
		$learningtypes = $this->Learningtype->find('list');
		$this->set(compact('learningtypes'));
		
		$this->loadModel('Studentinfo');
		$this->loadModel('Student');
		/*************************
		 * разибаем условие поиска
		 *************************/ 
		// debug($this->data['Search']);
		$selectedfacultet = '';
		$selectedprofession = '';
		$selectedcourse = '';
		$selectedgroup = '';
		$learningtype_id = $this->data['Search']['learningtype_id'];
		
		if (isset($this->data['Search']['facultet_id'])) {
			$selectedfacultet = $this->data['Search']['facultet_id'];
			
			
		} else {
			// добавляем если факультет не установлен то берем id факультета из facultets settings при условии что там один id
				
			$facultetsettings = $this->Session->read('FacultetsSettings');
			debug($this->data['Search']['facultet_id']);
			if (count($facultetsettings) == 1) {
				
				$selectedfacultet = $facultetsettings[0];
			} else {
				$selectedfacultet = 999;
			}
		}
		if (isset($this->data['Search']['profession_id'])) {
			$selectedprofession = $this->data['Search']['profession_id'];
		}
		if (isset($this->data['Search']['course_id'])) {
			$selectedcourse = $this->data['Search']['course_id'];
		}
		if (isset($this->data['Search']['studentgroup_id'])) {
			$selectedgroup = $this->data['Search']['studentgroup_id'];
		}
		$selectedgroups_ids = array();
		/********************************************************************************************/
		// выбран факультет спецальность курс группа
		/********************************************************************************************/
		if ($selectedfacultet && $selectedprofession && $selectedcourse && $selectedgroup) {
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroup), 'recursive' => 0));
			//формируем массив id групп
			array_push($selectedgroups_ids, $selectedgroup);
		}
		/********************************************************************************************/
		// выбран факультет специлальность курс
		/********************************************************************************************/
		else if ($selectedfacultet && $selectedprofession && $selectedcourse && !$selectedgroup) {
			// выбираем группы курса
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourse),
					'recursive' => 0,
					'order' => 'Studentgroup.id ASC',
					'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
			//	$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		/********************************************************************************************/
		// выбран факультет специальность
		/********************************************************************************************/
		else if ($selectedfacultet && $selectedprofession && !$selectedcourse && !$selectedgroup) {
			// выбираем курсы специальности
			$this->loadModel('Course');
			$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofession),
					'recursive' => 0,
					'order' => 'Course.id ASC',
					'fields' => array('Course.id')));
			$selectedcourses_ids = array();
			foreach ($selectedcourses as $element):
			array_push($selectedcourses_ids, $element['Course']['id']);
			endforeach;
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids),
					'recursive' => 0,
					'order' => 'Studentgroup.id ASC',
					'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
			//	$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		/********************************************************************************************/
		// выбран факультет
		/********************************************************************************************/
		if ($selectedfacultet && !$selectedprofession && !$selectedcourse && !$selectedgroup) {
			// выбираем специальности факультета
			$this->loadModel('Profession');
			$selectedprofessions = $this->Profession->find('all', array('conditions' => array('Profession.facultet_id' => $selectedfacultet), 'recursive' => 0));
			$selectedprofessions_ids = array();
			foreach ($selectedprofessions as $element):
			array_push($selectedprofessions_ids, $element['Profession']['id']);
			endforeach;
		//	debug($selectedprofessions_ids);
			// выбираем курсы специальностей
			$this->loadModel('Course');
			$selectedcourses = $this->Course->find('all', array('conditions' => array('Course.profession_id' => $selectedprofessions_ids),
					'recursive' => 0,
			//		'order' => 'Course.id ASC',
					'fields' => array('Course.id')));
			$selectedcourses_ids = array();
			foreach ($selectedcourses as $element):
			array_push($selectedcourses_ids, $element['Course']['id']);
			endforeach;
		//	debug($selectedcourses_ids);
			// выбираем группы курсов
			$this->loadModel('Studentgroup');
			$selectedgroups = $this->Studentgroup->find('all', array('conditions' => array('Studentgroup.course_id' => $selectedcourses_ids),
					'recursive' => 0,
			//		'order' => 'Studentgroup.id ASC',
					'fields' => array('Studentgroup.id')));
			//формируем массив id групп
			foreach ($selectedgroups as $element):
			array_push($selectedgroups_ids, $element['Studentgroup']['id']);
			endforeach;
			// выбираем студентов
			// $students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids), 'recursive' => 0));
		}
		//debug ($selectedgroups_ids);
		// выбираем всех студентов из этих групп
		$students_ids = array();
		
		if ($selectedgroups_ids && $learningtype_id){
			$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids, 'Student.learningtype_id' => $learningtype_id), 
																				'recursive' => -1, 'fields' => array('Student.id')));
			foreach($students as $student):
				array_push($students_ids, $student['Student']['id']);
			endforeach;
		} else if (!$selectedgroups_ids && $learningtype_id) {
			$students = $this->Student->find('all', array('conditions' => array('Student.learningtype_id' => $learningtype_id),
																				'recursive' => -1, 'fields' => array('Student.id')));
			foreach($students as $student):
			array_push($students_ids, $student['Student']['id']);
			endforeach;			
		} else if ($selectedgroups_ids && !$learningtype_id) {
			$students = $this->Student->find('all', array('conditions' => array('Student.studentgroup_id' => $selectedgroups_ids),
																							'recursive' => -1, 'fields' => array('Student.id')));
			foreach($students as $student):
			array_push($students_ids, $student['Student']['id']);
			endforeach;			
		}
		//debug($students_ids);
			
		// разоб поиска по studentinfo
		
		// фамилия
		$lastname = $this->data['Search']['lastname'];
		// имя
		$firstname = $this->data['Search']['firstname'];
		// год рождения
		$birth_year = $this->data['Search']['year']['year'];
		// месяц рождения
		$birth_month = $this->data['Search']['month']['month'];
		// день рождения
		$birth_day = $this->data['Search']['day']['day'];
		// серия паспорта
		$passport_ser = $this->data['Search']['passport_ser'];
		// номер паспорта
		$passport_num = $this->data['Search']['passport_num'];
		// номер личного дела (id студента)
		$student_id = $this->data['Search']['student_id'];
		// пол студента
		$gender_id = $this->data['Search']['gender_id'];
		// разибраем данные документа об образовании
		$edudoctype_id =  $this->data['Search']['educationdoctype_id'];
		$edudocdata = $this->data['Search']['educationdocdata'];
		// область по прописке
		$region_id = $this->data['Search']['region_id'];
		// разбираем область если это курская белгородская брянская липецкая орловская или тульская области
		// то ищем по всей области включая районы если это район то будем искать только по нему
		// 46 курская облатсь 
		// 31 белгородская область
		// 32 брянская область
		// 48 липецкая область
		// 57 орловская область
		// 71 тульская область
		
		switch ($region_id){
			case 46: $regions = array(46,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117); 
					$region_id = $regions; break;
			case 31: $regions = array(31,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138);
					$region_id = $regions; break;
			case 32: $regions = array(32,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165);
					$region_id = $regions; break;
			case 48: $regions = array(48,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183);
					$region_id = $regions; break;
			case 57: $regions = array(57,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207);
					$region_id = $regions; break;
			case 71: $regions = array(71,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231);
					$region_id = $regions; break;
		}
		// часть адреса по прописке
		$passport_adress = $this->data['Search']['passport_adress'];
		// определяем формат результата
		$format = $this->data['Search']['format'];
		
		// создаем массив поисковых ключей
		$search_conditions = array();
		if ($students_ids){
			array_push($search_conditions, array('Studentinfo.student_id' => $students_ids));
		} else {
			// условие чтобы по фаукльтету не выводились люди других факультетов
			array_push($search_conditions, array('Studentinfo.student_id' => 0));
		}
		if ($lastname){
			array_push($search_conditions, array('Studentinfo.lastname LIKE ' => $lastname.'%'));
		}
		if ($firstname){
			array_push($search_conditions, array('Studentinfo.firstname LIKE ' => $firstname.'%'));
		}	
		// многокомпонентное условие даты рождения	
		if ($birth_year && $birth_month && $birth_day){
			$birthdate = $birth_year.'-'.$birth_month.'-'.$birth_day;
			array_push($search_conditions, array('Studentinfo.birthdate LIKE ' => $birthdate.'%'));
		} else if ($birth_year && $birth_month && !$birth_day) {
			$birthdate = $birth_year.'-'.$birth_month;
			array_push($search_conditions, array('Studentinfo.birthdate LIKE ' => $birthdate.'%'));
		} else if (!$birth_year && $birth_month && $birth_day) {
			$birthdate = $birth_month.'-'.$birth_day;
			array_push($search_conditions, array('Studentinfo.birthdate LIKE ' => '%'.$birthdate.'%'));
		} else if ($birth_year && !$birth_month && $birth_day) {
			$birthdate = $birth_year.'-%-'.$birth_day;
			array_push($search_conditions, array('Studentinfo.birthdate LIKE ' => $birthdate));
		} else if ($birth_year && !$birth_month && !$birth_day) {
			$birthdate = $birth_year;
			array_push($search_conditions, array('Studentinfo.birthdate LIKE ' => $birthdate.'%'));			
		} else if (!$birth_year && $birth_month && !$birth_day){
			$birthdate = $birth_month;
			array_push($search_conditions, array('Studentinfo.birthdate LIKE ' => '%-'.$birthdate.'-%'));			
		} else if (!$birth_year && !$birth_month && $birth_day) {
			$birthdate = '-'.$birth_day;
			array_push($search_conditions, array('Studentinfo.birthdate LIKE ' => '%'.$birthdate));
		}
		// конец условия даты рождения
		if ($passport_ser) {
			array_push($search_conditions, array('Studentinfo.passport_ser LIKE ' => $passport_ser.'%'));
		}
		if ($passport_num) {
			array_push($search_conditions, array('Studentinfo.passport_num LIKE ' => $passport_num.'%'));
		}
		if ($student_id) {
			array_push($search_conditions, array('Studentinfo.student_id LIKE ' => $student_id.'%'));
		}
		if ($gender_id) {
			array_push($search_conditions, array('Studentinfo.gender_id LIKE ' => $gender_id.'%'));
		}	
		if ($edudoctype_id){
			array_push($search_conditions, array('Studentinfo.educationdoctype_id' => $edudoctype_id));
		}
		if ($edudocdata){
			array_push($search_conditions, array('Studentinfo.educationdocdata LIKE ' => '%'.$edudocdata.'%'));
		}
		if ($region_id) {
			array_push($search_conditions, array('Studentinfo.region_id' => $region_id));
		}		
		// адрес обрабатываем % с двух сторон
		if ($passport_adress) {
			array_push($search_conditions, array('Studentinfo.passport_adress LIKE ' => '%'.$passport_adress.'%'));
		}
		
		// debug($search_conditions);
		// закончили разбирать условие поиска
		$studentsinfos = $this->Studentinfo->find('all', array('conditions' => $search_conditions, 'recursive' => 0,
																	'fields' => array('Studentinfo.id', 
																						'Studentinfo.student_id',
																						'Studentinfo.lastname', 
																						'Studentinfo.firstname', 
																						'Studentinfo.surname', 
																						'Studentinfo.birthdate',
																						'Studentinfo.passport_ser', 
																						'Studentinfo.passport_num',
																						'Studentinfo.passport_adress',		
																						'Studentinfo.educationdoctype_id',
																						'Studentinfo.educationdocdata',
																						'Studentinfo.gender_id',
																						'Studentinfo.passport_adress',
																						)));

		$students_ids = array();
		foreach ($studentsinfos as $studentinfo):
			array_push($students_ids, $studentinfo['Studentinfo']['student_id']);
		endforeach;
		// debug ($students_ids);
		// выбираем записи из модели Student
		$this->set(compact('studentsinfos'));
			$students = $this->Studentinfo->Student->find('all', array('conditions' => array('Student.id' => $students_ids), 'recursive' => 0));
			$this->set('students', $students);
			
			$this->set('format', $format);
		// если выводим в файл значит подключить blank шаблон 	
			if (($format == 1) || ($format == 2)){
				$this->render('/', 'blank', 'findstudent');
			}
		
	}
}
?>